// SearchTask.cpp
#include "SearchTask.h"
#include <QDir>
#include <QFileInfoList>
#include <QMetaObject>
#include <QFileSystemModel>
#include <QDebug>
#include <QThread>
#include <thread>

#include "ConstValue.h"

SearchTask::SearchTask(MainWindow *mainWindow, const QList<QString> &list, const QString &searchText,bool isFolder)
    : m_mainWindow(mainWindow), m_path(list), m_searchText(searchText) {
    setAutoDelete(true);
}

void SearchTask::checkCurrentFolder(QList<QModelIndex> results, QDir dir) {
    QString dirPath = dir.absolutePath();
    if (dirPath.contains(m_searchText, Qt::CaseInsensitive)) {
        QModelIndex index = m_mainWindow->getModel()->index(dirPath);
        if (index.isValid()) {
            results.append(index);
        }
    }
}

bool SearchTask::checkStop() {
    if (M_Thread::isStop) {
        return true;
    }
    return false;
}

void SearchTask::run() {
    QList<QModelIndex> results;
    qDebug() <<QThread::currentThreadId()<< "开始搜索:" << m_path << "关键词:" << m_searchText;
    if (isFolder) {
        //判断终止标志，停止搜索
        for (const auto& path:m_path) {
            if (checkStop()) break;
            //先判断当前路径是不包含
            QDir dir(path);
            if (!dir.exists()) {
                continue;
            }
            checkCurrentFolder(results, dir);
            searchRecursively(dir, results, 0, M_Search::maxDepth, M_Search::maxResults);
        }
    }else {
        for (const auto& filePath:m_path) {
            if (checkStop()) break;
            if (filePath.contains(m_searchText, Qt::CaseInsensitive)) {
                QModelIndex index = m_mainWindow->getModel()->index(filePath);
                if (index.isValid()) {
                    results.append(index);
                }
            }
        }
    }

    qDebug() <<QThread::currentThreadId()<< "搜索完成，找到" << results.size() << "个结果";
    QMetaObject::invokeMethod(m_mainWindow, "handleRunnableResult",
                             Qt::QueuedConnection,
                             Q_ARG(QList<QModelIndex>, results));
}

/**
 * 递归搜索
 * @param dir 目录路径
 * @param results 结果集
 * @param currentDepth 当前深度
 * @param maxDepth 最大深度
 * @param maxResults 最大结果数
 */
void SearchTask::searchRecursively(const QDir &dir, QList<QModelIndex> &results,
                                   int currentDepth, int maxDepth, int maxResults) {
    if (checkStop()) return;
    if (currentDepth > maxDepth) {
        return;
    }
    if (results.size() >= maxResults) {
        return;
    }

    //递归搜索子文件夹
    QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    for (const QFileInfo &info : entries) {
        if (results.size() >= maxResults) {
            return;
        }
        QString fileName = info.fileName();
        if (fileName.contains(m_searchText, Qt::CaseInsensitive)) {
            QModelIndex index = m_mainWindow->getModel()->index(info.absoluteFilePath());
            if (index.isValid()) {
                results.append(index);
            }
        }
        if (info.isDir()) {
            QDir subDir(info.absoluteFilePath());
            searchRecursively(subDir, results, currentDepth + 1, maxDepth, maxResults);
        }
    }
}
